﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseManager.Utilities
{
    public class DbExceptionHelper
    {

        // 辅助方法：判断是否为数据库关闭 / 无法连接的异常
        public static bool IsDatabaseShutdownException(Exception ex)
        {
            // MySQL 连接失败的典型错误消息（不同驱动可能略有差异）
            string[] shutdownKeywords = {
            "无法连接到任何指定的 MySQL 主机", // MySql.Data 驱动
            "No connection could be made because the target machine actively refused it", // MySqlConnector 驱动
            "Unable to connect to any of the specified MySQL hosts",
            "Host is not reachable",
            "数据库连接失败：拒绝连接"
            };

            // 递归检查内部异常（异常可能被包装多层）
            Exception currentEx = ex;
            while (currentEx != null)
            {
                if (shutdownKeywords.Any(keyword => currentEx.Message.Contains(keyword)))
                {
                    return true;
                }
                currentEx = currentEx.InnerException;
            }
            return false;
        }

        // 辅助方法：判断是否为连接字符串错误（如服务器地址、端口错误）
        public static bool IsConnectionStringError(Exception ex)
        {
            string[] configErrorKeywords = {
                "Unknown MySQL server host", // 主机不存在
                "Port 3306 failed", // 端口错误
                "无法解析主机地址"
                };

            Exception currentEx = ex;
            while (currentEx != null)
            {
                if (configErrorKeywords.Any(keyword => currentEx.Message.Contains(keyword)))
                {
                    return true;
                }
                currentEx = currentEx.InnerException;
            }
            return false;
        }

        // 辅助方法：判断是否为权限 / 密码错误
        public static bool IsPermissionError(Exception ex)
        {
            string[] authErrorKeywords = {
                "Access denied for user", // 权限不足
                "密码错误",
                "authentication failed"
                };

            Exception currentEx = ex;
            while (currentEx != null)
            {
                if (authErrorKeywords.Any(keyword => currentEx.Message.Contains(keyword)))
                {
                    return true;
                }
                currentEx = currentEx.InnerException;
            }
            return false;
        }
    }
}
